package qc.module.iot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.common.core.utils.LocalDateTimeUtil;
import qc.module.iot.entity.IotChannel;
import qc.module.iot.repository.IotChannelRepository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Iot通信信道Service
 *
 * @author QuCheng Tech
 * @since 2025/11/19
 */
@Service
public class IotChannelService {
    private static final Logger logger = LoggerFactory.getLogger(IotChannelService.class);

    @Autowired
    private IotChannelRepository repository;

    /**
     * 获取所有通信信道集合
     *
     * @return java.util.List<qc.module.iot.entity.IotChannel>
     * @author QuCheng Tech
     * @since 2025/11/19
     */
    public List<IotChannel> getAll() {
        LambdaQueryWrapper<IotChannel> wrapper = new LambdaQueryWrapper<>();

        //排序，按通道名称
        wrapper.orderByAsc(IotChannel::getName);

        //查询数据
        List<IotChannel> ens = repository.selectList(wrapper);
        if (ens != null && ens.size() > 0x0)
            return ens;

        return null;
    }

    /**
     * 更新指定通道的最新通讯时间，最新通讯包括建立连接、发送心跳/注册报文
     *
     * @param channelId 通道ID
     * @return java.lang.String
     * @author QuCheng Tech
     * @since 2025/11/19
     */
    public String updateLatestCommunicateTime(String channelId) {
        if (StringUtils.isNotBlank(channelId)) {
            LocalDateTime now = LocalDateTimeUtil.getNow();

            LambdaUpdateWrapper<IotChannel> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(IotChannel::getCmtm, now);

            //条件：id相等
            updateWrapper.eq(IotChannel::getId, channelId);

            repository.update(null, updateWrapper);
        }

        return QCUnifyReturnValue.Success();
    }

    /**
     * 更新指定通道的最新接收报文时间(同时更新最新通讯时间)
     *
     * @param channelId 通道ID
     * @return java.lang.String
     * @author QuCheng Tech
     * @since 2025/11/19
     */
    public String updateLatestReceivePacketsTime(String channelId) {
        if (StringUtils.isNotBlank(channelId)) {
            LocalDateTime now = LocalDateTimeUtil.getNow();

            LambdaUpdateWrapper<IotChannel> updateWrapper = new LambdaUpdateWrapper<>();
            //同时更新最新通讯时间和最后接收数据时间
            updateWrapper.set(IotChannel::getCmtm, now);
            updateWrapper.set(IotChannel::getPcktm, now);

            //条件：id相等
            updateWrapper.eq(IotChannel::getId, channelId);

            repository.update(null, updateWrapper);
        }

        return QCUnifyReturnValue.Success();
    }
}
